package com.ai.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * 时间工具类
 * Mr.chen
 */
public class TimeUtils {

    // 获取当前时间的毫秒数
    public static long currentTimeMillis() {
        return System.currentTimeMillis();
    }

    // 获取当前时间的 Date 对象
    public static Date currentDate() {
        return new Date();
    }

    // 将时间戳转换为 Date 对象
    public static Date timestampToDate(long timestamp) {
        return new Date(timestamp);
    }

    // 将 Date 对象转换为指定格式的字符串
    public static String dateToString(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        sdf.setTimeZone(TimeZone.getDefault());
        return sdf.format(date);
    }

    // 将指定格式的字符串转换为 Date 对象
    public static Date stringToDate(String str, String pattern) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        sdf.setTimeZone(TimeZone.getDefault());
        return sdf.parse(str);
    }

    // 获取指定日期的前一天的日期
    public static Date getPreviousDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);
        return calendar.getTime();
    }

    // 获取指定日期的后一天的日期
    public static Date getNextDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, 1);
        return calendar.getTime();
    }


    public static void main(String[] args) throws Exception {
        // 获取当前时间的毫秒数
        long currentTimeMillis = TimeUtils.currentTimeMillis();
        System.out.println("Current Time Millis: " + currentTimeMillis);

        // 获取当前时间的 Date 对象
        Date currentDate = TimeUtils.currentDate();
        System.out.println("Current Date: " + currentDate);

        // 将时间戳转换为 Date 对象
        Date timestampDate = TimeUtils.timestampToDate(currentTimeMillis);
        System.out.println("Timestamp Date: " + timestampDate);

        // 将 Date 对象转换为指定格式的字符串
        String dateString = TimeUtils.dateToString(currentDate, "yyyy-MM-dd HH:mm:ss");
        System.out.println("Date String: " + dateString);

        // 将指定格式的字符串转换为 Date 对象
        Date stringDate = TimeUtils.stringToDate("2023-03-28 14:30:00", "yyyy-MM-dd HH:mm:ss");
        System.out.println("String Date: " + stringDate);

        // 获取指定日期的前一天的日期
        Date previousDate = TimeUtils.getPreviousDate(currentDate);
        System.out.println("Previous Date: " + previousDate);

        // 获取指定日期的后一天的日期
        Date nextDate = TimeUtils.getNextDate(currentDate);
        System.out.println("Next Date: " + nextDate);
    }

}
